package user_api

import (
	"ginBolg/global"
	"ginBolg/models"
	"ginBolg/models/res"
	"ginBolg/utils"
	"ginBolg/utils/jwt"
	"github.com/gin-gonic/gin"
)

type UpdatePasswordRequest struct {
	OldPwd string `json:"oldPwd" binding:"required" msg:"请输入旧密码"`
	Pwd    string `json:"pwd" binding:"required" msg:"请输入新密码"`
}

func (UserApi) UserPasswordUpdate(c *gin.Context) {
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwt.CustomClaims)
	var cr UpdatePasswordRequest
	if err := c.ShouldBindJSON(&cr); err != nil {
		res.FailWithError(err, &cr, c)
		return
	}
	var user models.UserModel
	err := global.DB.Take(&user, claims.UserId).Error
	if err != nil {
		res.Fail("用户不存在", c)
		return
	}
	// 判断密码是否一致
	if !utils.ComparePasswords(user.Password, cr.OldPwd) {
		res.Fail("原密码错误", c)
		return
	}
	hashPwd := utils.HashAndSalt(cr.Pwd)
	err = global.DB.Model(&user).Update("password", hashPwd).Error
	if err != nil {
		global.Log.Error(err)
		res.Fail("修改失败", c)
		return
	}
	res.OkWithMessage("修改成功", c)
	return
}
